<template>
  <div class="minsu-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入民宿名称或地址"
        clearable
        class="search-input"
      />
      <el-button type="primary" @click="bookHistory">查看预订记录</el-button>
    </div>

    <!-- 民宿展示区域 -->
    <div class="minsu-grid">
      <el-card
        v-for="(minsu, index) in filteredMinsu"
        :key="index"
        class="minsu-card"
      >
        <div class="image-wrapper">
          <img :src="minsu.coverpicture || defaultImage" class="minsu-image" />
        </div>
        <div class="info">
          <h3 class="name">{{ minsu.hname }}</h3>
          <p class="address">地址: {{ minsu.address }}</p>
          <p class="price">价格: ￥{{ minsu.price }} / 晚</p>
          <p class="rating">评分: {{ minsu.grade }} ⭐</p>
          <p class="rating_status">评价: {{ minsu.gradeStatus }}</p>
          <p class="category">分类: {{ classifyPrice(minsu.price) }}</p>
          <p
            class="stock"
            :class="{ 'low-stock': minsu.stock < 5 }"
          >
            库存: {{ minsu.stock }} {{ minsu.stock < 5 ? '(库存紧张)' : '' }}
          </p>
          <p class="phonenumber">电话: {{ minsu.phonenumber }}</p>
        </div>
        <div class="actions">
          <el-button type="success" @click="reserveMinsu(minsu)" :disabled="minsu.stock <= 0">
            {{ minsu.stock > 0 ? '预订' : '售罄' }}
          </el-button>
        </div>
      </el-card>
    </div>

  <!-- 预订记录弹窗 -->
  <el-dialog title="预订记录" :visible.sync="showRecordDialog" width="50%" center>
        <div v-if="BookRecords.length > 0">
          <el-card v-for="(record, index) in BookRecords" :key="index">
            <p>民宿名称: {{ record.hname }}</p>
            <p>预订时间: {{ record.bookTime }}</p>
          </el-card>
        </div>
        <p v-else style="text-align: center;">暂无购买记录</p>
      </el-dialog>

    <!-- 预订成功弹窗 -->
    <el-dialog
      title="预订成功"
      :visible.sync="showReserveDialog"
      width="30%"
      center
    >
      <p>您已成功预订 {{ reservedMinsu.hname }}</p>
      <p>地址: {{ reservedMinsu.address }}</p>
      <p>价格: ￥{{ reservedMinsu.price }} / 晚</p>
      <p>电话: {{ reservedMinsu.phonenumber }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeReserveDialog">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectAllHomeStay,bookHomeStay,bookHotelRecords } from "@/api/homestay.ts";
export default {
  data() {
    return {
      searchQuery: "", // 搜索框内容
      minsuList: [],
      defaultImage: "https://via.placeholder.com/300x200?text=默认图片",
      showReserveDialog: false,
      reservedMinsu: {},
      BookRecords:'',
      showRecordDialog:false
    };
  },
  mounted() {
    // 页面加载时调用 API 获取民宿数据
      this.flash();
  },
  computed: {
    // 根据搜索内容过滤民宿
    filteredMinsu() {
      const query = this.searchQuery.trim().toLowerCase();
      return this.minsuList.filter(
        (minsu) =>
          minsu.hname.toLowerCase().includes(query) ||
          minsu.address.toLowerCase().includes(query)
      );
    },
  },
  methods: {
    flash(){
      selectAllHomeStay()
      .then((result) => {
        if (result.data.code === 1) {
          this.minsuList = result.data.data.map((item) => ({
            ...item,
          }));
        }
      })
      .catch((err) => {
        console.error("获取民宿数据失败", err);
      });
    },
    // 分类价格
    classifyPrice(price) {
      if (price < 500) return "经济型";
      if (price < 700) return "中等型";
      return "豪华型";
    },
    // 预订民宿
    reserveMinsu(minsu) {
    this.reservedMinsu=minsu;
     
      if (minsu.stock > 0) {
        const formData=new FormData;
      formData.append("bookhotelrecord",JSON.stringify({
        hid:minsu.hid,
        uid:JSON.parse(localStorage.getItem("currentUser")).uid,
        hname:minsu.hname,
        fid:minsu.fid
      }))
        bookHomeStay(formData)
        .then(res => {
          if (res.data.code === 1) {
            
            this.$message.success("预定成功！");
            this.flash();
            this.showReserveDialog=true;
          } else {
            this.$message.error(res.data.message || "预定失败！");
          }
        })
        .catch(error => {
          console.error("上传失败", error);
          this.$message.error("上传失败，请重试！");
        });
      }
    },
    // 关闭预订成功弹窗
    closeReserveDialog() {
      this.showReserveDialog = false;
    },
    //预订记录
    bookHistory(){
      bookHotelRecords(JSON.parse(localStorage.getItem("currentUser")).uid)
        .then(res => {
          if (res.data.code === 1) {
            this.BookRecords=res.data.data;
            this.showRecordDialog=true;
          } else {
            this.$message.error(res.data.message || "查看失败！");
          }
        })
        .catch(error => {
          console.error("查看失败", error);
          this.$message.error("查看失败，请重试！");
        });
    }
  },
};
</script>

<style>
.minsu-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 400px;
}

.minsu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.minsu-card {
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.2s;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.minsu-card:hover {
  transform: translateY(-5px);
}

.image-wrapper {
  width: 100%;
  height: 150px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.minsu-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.info {
  padding: 10px;
}

.name {
  font-size: 18px;
  font-weight: bold;
  margin: 5px 0;
}

.address,
.price,
.rating,
.rating_status,
.stock,
.category {
  font-size: 14px;
  color: #666;
}

.price {
  color: #f56c6c;
}

.stock {
  font-weight: bold;
}

.low-stock {
  color: red;
}

.actions {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>
